package free6om.research.qart4j;

/**
 * @Copyright © 2017 sanbo Inc. All rights reserved.
 * @Description: 长方形。个人理解是二维码区域
 * @Version: 1.0
 * @Create: 7/30/15
 * @Author: free6om
 * @Create: 2017年12月27日 下午3:41:05
 * @Modifier: free6om
 */
public class Rectangle {
    public Point start;
    public int width;
    public int height;

    public Rectangle(Point start, int width, int height) {
        this.start = start;
        this.width = width;
        this.height = height;
    }

    public void setStart(Point start) {
        this.start = start;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    /**
     * 相交处理？
     * 
     * @param other
     * @return
     */
    public Rectangle intersect(Rectangle other) {
        if (other == null || other.start == null || this.start == null) {
            return null;
        }

        // not intersect
        if (other.start.x >= this.start.x + width || other.start.x + other.width <= this.start.x || other.start.y >= this.start.y + this.height
                || other.start.y + other.height <= this.start.y) {
            return null;
        }

        int startX = Math.max(this.start.x, other.start.x);
        int width = Math.min(this.start.x + this.width, other.start.x + other.width) - startX;
        int startY = Math.max(this.start.y, other.start.y);
        int height = Math.min(this.start.y + this.height, other.start.y + other.height) - startY;

        return new Rectangle(new Point(startX, startY), width, height);
    }

    /**
     * 联盟？应该是覆盖。
     * 
     * @param other
     * @return
     */
    public Rectangle union(Rectangle other) {
        if (other == null || other.start == null || this.start == null) {
            return null;
        }

        int startX = Math.min(other.start.x, this.start.x);
        int startY = Math.min(other.start.y, this.start.y);
        int width = Math.max(other.start.x + other.width, this.start.x + this.width) - startX;
        int height = Math.max(other.start.y + other.height, this.start.y + this.height) - startY;

        return new Rectangle(new Point(startX, startY), width, height);
    }
}
